import { useEffect, useState } from "react";
import {
  NavBar,
  Icon,
  WingBlank,
  WhiteSpace,
  InputItem,
  Button,
  Toast,
} from "antd-mobile";

import { reqSendCode, reqVerifyCode } from "../../../api/register";
import { codeReg } from "../../../utils/regs";
import msg from "./msg.png";
import "./index.less";

// 倒计时最大时间
const MAX_TIME = 60;

function CodeRegister({ history, location }) {
  // 倒计时的时间
  const [time, setTime] = useState(MAX_TIME);
  // 是否发送过验证码
  const [isSendCode, setIsSendCode] = useState(true);
  // 验证码
  const [code, setCode] = useState("");
  const [isDisabled, setIsDisabled] = useState(true);
  /*
    useEffect可以使用多次，互相不会影响
  */
  useEffect(() => {
    // 倒计时效果
    setTimeout(() => {
      if (time === 1) {
        setIsSendCode(false);
        return;
      }
      setTime(time - 1);
    }, 1000);
  }, [time]);

  useEffect(() => {
    // 发送验证码
    reqSendCode(location.state);
  }, [location.state]);

  const sendCode = async () => {
    try {
      // 启用倒计时
      setTime(MAX_TIME);
      setIsSendCode(true);
      // 发送验证码
      await reqSendCode(location.state);
    } catch (e) {
      console.log(e);
    }
  };

  // 收集验证码
  const handleInputChange = (val) => {
    if (codeReg.test(val)) {
      setIsDisabled(false);
    } else {
      setIsDisabled(true);
    }
    setCode(val);
  };

  const next = async () => {
    // 验证验证码是否正确
    const phone = location.state;
    const res = await reqVerifyCode(phone, code);
    // console.log(res);
    if (res.data.code === 20000) {
      // ok
      history.push("/register/password", phone);
    } else {
      Toast.fail(res.data.message, 2);
    }
  };

  return (
    <div className="verify-code">
      <NavBar
        mode="light"
        icon={<Icon className="icon-left" type="left" />}
        onLeftClick={() => history.goBack()}>
        硅谷注册
      </NavBar>
      <WingBlank>
        <img className="verify-code-msg" src={msg} alt="msg" />
        <p className="verify-code-tip">
          我们将以短信或电话的形式将验证码发送给您，请注意接听0575/025/0592/010等开头的电话
        </p>
        <div className="verify-code-container">
          <InputItem
            className="input-item"
            placeholder="请输入手机验证码"
            value={code}
            onChange={handleInputChange}
          />
          {isSendCode ? (
            <Button
              className="verify-code-btn verify-code-btn-disabled"
              disabled>
              重新发送({time}s)
            </Button>
          ) : (
            <Button className="verify-code-btn" onClick={sendCode}>
              发送验证码
            </Button>
          )}
        </div>
        <WhiteSpace size="xl" />
        <Button
          disabled={isDisabled}
          type="primary"
          className="btn"
          onClick={next}>
          下一步
        </Button>
        <span className="verify-code-question">
          遇到问题?请<span>联系客服</span>
        </span>
      </WingBlank>
    </div>
  );
}

export default CodeRegister;
